package com.clhbolg.service.impl;

import com.clhbolg.domain.UserInfo;
import com.clhbolg.enums.FilePathEnum;
import com.clhbolg.mapper.UserInfoMapper;
import com.clhbolg.model.vo.request.SubscribeVO;
import com.clhbolg.model.vo.request.UserInfoVO;
import com.clhbolg.service.IUserInfoService;
import com.clhbolg.strategy.context.UploadStrategyContext;
import com.clhbolg.util.UserBuilderUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author cailinhu
 * @date 2023-02-08
 */
@RequiredArgsConstructor
@Service
public class UserInfoServiceImpl implements IUserInfoService {

    private final UserInfoMapper baseMapper;
    @Autowired
    UploadStrategyContext uploadStrategyContext;

    @Autowired
    ISysUserService sysUserService;

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void updateUserInfo(UserInfoVO userInfoVO, Long userId ){
        //2.再修改自己的info表
        UserInfo userInfo = UserBuilderUtil.builderUserInfo(userInfoVO);
        userInfo.setId(userId);
        baseMapper.updateById(userInfo);
    }


    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void insertUserInfo(SysUser sysUser) {
        //记录userInfo
        UserInfo userInfo = UserBuilderUtil.builderUserInfo(sysUser);
        baseMapper.insert(userInfo);
    }

    @Override
    @Transactional
    public String updateAvatar(MultipartFile file) {
        String path = uploadStrategyContext.executeUploadStrategy(file, FilePathEnum.AVATAR.getPath());
        Long userId = LoginHelper.getUserId();
        UserInfo userInfo = UserInfo.builder()
            .id(userId)
            .avatar(path)
            .build();
        baseMapper.updateById(userInfo);
        sysUserService.updateUserAvatar(LoginHelper.getUsername(),path);
        return path;
    }

    @Override
    public void updateUserSubscribe(SubscribeVO subscribeVO) {
        UserInfo userInfo = UserInfo.builder()
            .id(subscribeVO.getUserId()).isSubscribe(subscribeVO.getIsSubscribe())
            .build();
        baseMapper.updateById(userInfo);
    }
}
